import { MinusOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, InputNumber } from 'antd';
import React, { useMemo, useState, useEffect } from 'react';
import { useContextSelector } from 'use-context-selector';

import { WorkflowContext } from '../../../../../context';

import type { RenderInputProps } from '../type';

const NumberInputRender = ({ item, nodeId }: RenderInputProps) => {
  const onChangeNode = useContextSelector(WorkflowContext, (v) => v.onChangeNode);

  const [value, setValue] = useState(item.value ?? item.defaultValue ?? 0);

  useEffect(() => {
    onChangeNode({
      nodeId,
      type: 'updateInput',
      key: item.key,
      value: {
        ...item,
        value: Number(value),
      },
    });
  }, [value, item, nodeId, onChangeNode]);

  const Render = useMemo(() => {
    return (
      <div className="flex items-center gap-1">
        <Button
          size="small"
          className="h-6 w-6 rounded-full"
          icon={<MinusOutlined size={8} />}
          onClick={() => {
            if (value > (item.min ?? 0)) {
              setValue(value - 1);
            }
          }}
        />
        <InputNumber
          defaultValue={item.value}
          value={value}
          min={item.min}
          max={item.max}
          height={24}
          width={64}
          style={{
            width: '64px',
          }}
          size="small"
          controls={false}
          className="workflow-input"
          onChange={setValue}
        />
        <Button
          size="small"
          className="h-6 w-6 rounded-full"
          icon={<PlusOutlined />}
          onClick={() => {
            if (value < (item.max ?? 9999)) {
              setValue(value + 1);
            }
          }}
        />
      </div>
    );
  }, [item, value, setValue]);

  return Render;
};

export default React.memo(NumberInputRender);
